package com.changzhu.community.controller;

import com.changzhu.community.entity.User;
import com.changzhu.community.service.UserService;
import com.changzhu.community.util.ExcelFileUtil;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Map;

import static com.changzhu.community.util.CommunityConstant.*;

@Controller
public class LoginController {

    private static final Logger logger= LoggerFactory.getLogger(LoginController.class);

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    UserService userService;

    @Autowired
    ExcelFileUtil fileUtil;


    @Autowired
    private Producer kaptchaProducer;

    /**
     * 获取请求页面
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String getRigsterPage(){
        return "site/register";
    }

    /**
     *处理注册请求
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(Model model, User user){
        Map<String,Object> map=userService.register(user);
        if(map.isEmpty()||map==null){
           model.addAttribute("msg","注册成功，我们已经向您的邮箱发送了邮件，请尽快激活");
           model.addAttribute("target","index");
           return "site/operate-result";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "site/register";
        }
    }

    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId")int userId,@PathVariable("code")String code){
        int result=userService.activation(userId,code);
        switch (result){
            case ACTIVATION_SUCCESS:
            {
                model.addAttribute("msg","账号已激活,可以正常使用了!");
                model.addAttribute("target","/login");
                break;
            }
            case ACTIVATION_REPEAT:
            {
                model.addAttribute("msg","无效操作,该账号已经激活过了!");
                model.addAttribute("target","/index");
            }
            case ACTIVATION_FAILED:
            {
                model.addAttribute("msg","激活失败,您提供的激活码部正确");
                model.addAttribute("target","/index");
            }
            default:
        }
        return "site/operate-result";
    }


    /**
     * 生成验证码
     * 敏感信息直接存session
     * @param response
     * @param session
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        //根据配置生成验证码字符串
        String text=kaptchaProducer.createText();
        //生成与之对应的图片
        BufferedImage image=kaptchaProducer.createImage(text);

        //将验证码存入到session
        session.setAttribute("kaptcha",text);

        //将图片输出给浏览器
        response.setContentType("image/png");
        try{
            OutputStream os=response.getOutputStream();
            ImageIO.write(image,"png",os);
        }catch (Exception e){
            logger.error("响应验证码失败"+e.getMessage());
        }

    }

    @PostMapping("/login")
    public String login(String username, String password, String code,
                        boolean remeberme,
                        Model model,
                        HttpServletResponse response,
                        HttpSession session){
        //1.检查验证码
        String kaptcha= (String) session.getAttribute("kaptcha");
        if(StringUtils.isBlank(kaptcha)||StringUtils.isBlank(code)||!kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码不正确");
            return "site/login";
        }

        //2.检查账号,密码
        int expireSeconds=remeberme?REMEMBER_EXPIRED_SECONDS:DEFAULT_EXPIRED_SECONDS;
        //3.登陆,凭证录入到数据库中
        Map<String,Object> map=userService.login(username,password,expireSeconds);
        //若登陆成功,跳转到首页页面
        String key="ticket";
        if(map.containsKey(key)){
            Cookie cookie=new Cookie(key,map.get(key).toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expireSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "site/login";
        }
    }

    @GetMapping("/login")
    public String getLoginPage(){
        return "site/login";
    }

}
